from google.appengine.ext import webapp
from google.appengine.ext import blobstore
from google.appengine.ext import db

import re

from utils import *
from datatypes import *
from CONFIG import *

"""
Handles requests for /manage. Shows the management
console.
"""
class ManageHandler(webapp.RequestHandler):

    @login_required
    @admin_required
    def get(self):
        writeHeader(self, "gapycdn - management console")

        templateData = {}

        # Generate an upload URL
        templateData["upload_url"] = blobstore.create_upload_url(GAPYCDN_CONFIG["base_url"] + "upload")

        # Get root directory, or the one passed via get
        if self.request.get("dir") == "":
            root = Directory.get_root()
        else:
            root = Directory.get_by_id(int(self.request.get("dir")))
        templateData["current_path"] = htmlise_path(root.path())
        templateData["current_directory_id"] = str(root.key().id())

        # Get the Assets from the database.
        templateData["assets"] = db.GqlQuery("SELECT * FROM Asset WHERE directory = :d", d = root)

        templateData["directories"] = []
        
        for d in root.dir():
            path = htmlise_path(d.path())
            tup = (path, d.key().id())
            templateData["directories"].append(tup)

        # Write out the manage template
        self.response.out.write(template.render(getTemplatePath("manage"), templateData))
        
        writeFooter(self)
